package cn.itcast.robot;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityOptionsCompat;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import cn.itcast.AppConfig;
//import cn.itcast.
//import cn.imu.intelRobot.R;
//import cn.itcast.R;
import cn.itcast.utils.HttpUtil;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;


public class RegisterActivity extends AppCompatActivity {
    private static Spinner academySpinner = null;  //学院
    private static Spinner gradeSpinner = null; 	//年级
    private static Spinner classesSpinner = null;	//班级
    private static ArrayAdapter<String> academyAdapter = null;  //学院适配器
    private static ArrayAdapter<String> gradeAdapter = null;	//年级适配器
    private static ArrayAdapter<String> classesAdapter = null;	//班级适配器
    //学院选项值
    private List<String> academy = new ArrayList<String>();
    private List<String> academyid = new ArrayList<String>();
    //年级选项值
    private static List<String> grade = new ArrayList<String>();
    private static List<String> gradeid = new ArrayList<String>();

    //班级选项值
    private static List<String> classes = new ArrayList<String>();
    private static List<String> classesid = new ArrayList<String>();

    private String selectedclassesId;
    private Integer sex = new Integer(0);


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        academySpinner = (Spinner) findViewById(R.id.spin_academy);
        gradeSpinner = (Spinner) findViewById(R.id.spin_grade);
        classesSpinner= (Spinner) findViewById(R.id.spin_classes);
        Button registerButton = (Button) findViewById(R.id.registerButton);

        EditText usernameEditText = (EditText) findViewById(R.id.usernameEditText);
        EditText nicknameEditText = (EditText) findViewById(R.id.nicknameEditText);
        RadioButton sex_man = (RadioButton) findViewById(R.id.sex_man);
        RadioButton sex_woman = (RadioButton) findViewById(R.id.sex_woman);
        EditText passwordEditText = (EditText) findViewById(R.id.passwordEditText);
        EditText confirmpwdEditText = (EditText) findViewById(R.id.confirmpwdEditText);
        EditText emailEditText = (EditText) findViewById(R.id.emailEditText);
        EditText phoneEditText = (EditText) findViewById(R.id.phoneEditText);


        HttpUtil.get(AppConfig.host + "/classes/api/list?parentId=100", new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(RegisterActivity.this, "服务器通信失败", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String responseData = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            JSONObject jsonObject = new JSONObject(responseData);
                            if (jsonObject.getString("code").equals("200")) {
                               getArray(jsonObject,academy,academyid);
                                //绑定适配器和值
                                academyAdapter = new ArrayAdapter<String>(RegisterActivity.this,
                                        R.layout.spinner_item ,academy);
                                academySpinner.setAdapter(academyAdapter);
                                academySpinner.setSelection(0,true);  //设置默认选中项，此处为默认选中第0个值
                            }
                            else
                            {
                                Toast.makeText(RegisterActivity.this, jsonObject.getString("msg"), Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        });
        sex_man.setChecked(true);
        sex_man.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sex_woman.setChecked(false);
                sex_man.setChecked(true);
                sex = 0;
            }
        });
        sex_woman.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sex_man.setChecked(false);
                sex_woman.setChecked(true);
                sex = 2;
            }
        });

        //学院下拉框监听
        academySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
        {

            // 表示选项被改变的时候触发此方法，主要实现办法：动态改变年级适配器的绑定值
            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long arg3)
            {
                gradeid.clear();
                grade.clear();
                Log.d("HttpUtil.get", ""+academyid.get(position));
                HttpUtil.get(AppConfig.host + "/classes/api/list?parentId="+academyid.get(position), new Callback() {

                    @Override
                    public void onFailure(Call call, IOException e) {
                        e.printStackTrace();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(RegisterActivity.this, "服务器通信失败", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        final String responseData = response.body().string();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    JSONObject jsonObject = new JSONObject(responseData);
                                    if (jsonObject.getString("code").equals("200")) {
                                        getArray(jsonObject,grade,gradeid);
                                        //将年级适配器的值改变为grade中的值
                                        gradeAdapter = new ArrayAdapter<String>(
                                                RegisterActivity.this, R.layout.spinner_item, grade);
                                        // 设置二级下拉列表的选项内容适配器
                                        gradeSpinner.setAdapter(gradeAdapter);
                                    }
                                    else
                                    {
                                        Toast.makeText(RegisterActivity.this, jsonObject.getString("msg"), Toast.LENGTH_SHORT).show();
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                    }
                });


            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0)
            {

            }

        });


        //年级下拉监听
        gradeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
        {

            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                                       int position, long arg3)
            {
                classes.clear();
                classesid.clear();
                HttpUtil.get(AppConfig.host + "/classes/api/list?parentId="+gradeid.get(position), new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        e.printStackTrace();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(RegisterActivity.this, "服务器通信失败", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        final String responseData = response.body().string();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    JSONObject jsonObject = new JSONObject(responseData);
                                    if (jsonObject.getString("code").equals("200")) {
                                        getArray(jsonObject,classes,classesid);
                                        //将班级适配器的值改变为grade中的值
                                        classesAdapter = new ArrayAdapter<String>(
                                                RegisterActivity.this, R.layout.spinner_item, classes);
                                        // 设置三级下拉列表的选项内容适配器
                                        Log.d("classes", ""+classes);
                                        Log.d("classesid", ""+classesid);
                                        Log.d("OnItemSel", "classesAdapter"+classesAdapter);
                                        classesSpinner.setAdapter(classesAdapter);
                                    }
                                    else
                                    {
                                        Toast.makeText(RegisterActivity.this, jsonObject.getString("msg"), Toast.LENGTH_SHORT).show();
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                    }
                });
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0)
            {

            }
        });

        //设置班级下拉监听
        classesSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                selectedclassesId = classesid.get(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });


        //设置注册按钮的监听事件
        registerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String username = usernameEditText.getText().toString();
                String nickname = nicknameEditText.getText().toString();
                String password = passwordEditText.getText().toString();
                String confirmpwd = confirmpwdEditText.getText().toString();
                String email = emailEditText.getText().toString();
                String phone = phoneEditText.getText().toString();

                if(username == null || username.equals(""))
                {
                    Toast.makeText(RegisterActivity.this,"用户名不能为空",Toast.LENGTH_SHORT).show();
                }
                else if(password == null || password.equals(""))
                {
                    Toast.makeText(RegisterActivity.this,"密码不能为空",Toast.LENGTH_SHORT).show();
                }
                else if(nickname == null || nickname.equals(""))
                {
                    Toast.makeText(RegisterActivity.this,"姓名不能为空",Toast.LENGTH_SHORT).show();
                }
                else if(confirmpwd == null || confirmpwd.equals(""))
                {
                    Toast.makeText(RegisterActivity.this,"确认密码不能为空",Toast.LENGTH_SHORT).show();
                }
                else if(!password.equals(confirmpwd))
                {
                    Toast.makeText(RegisterActivity.this,"两次输入密码不一致",Toast.LENGTH_SHORT).show();
                }
                else if(selectedclassesId == null)
                {
                    Toast.makeText(RegisterActivity.this,"请选择所在班级",Toast.LENGTH_SHORT).show();
                }
                else {
                    Map<String,String> data = new HashMap<>();
                    data.put("userName",username);
                    data.put("password",password);
                    data.put("classesId",selectedclassesId);
                    data.put("nickName",nickname);
                    data.put("email",email);
                    data.put("phonenumber",phone);
                    data.put("sex",sex.toString());
                    data.put("status","0");
                    data.put("createBy","内大考研");

                    HttpUtil.post(AppConfig.host + "/app/user/api/register", data, new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            e.printStackTrace();
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(RegisterActivity.this, "服务器通信失败", Toast.LENGTH_SHORT).show();
                                }
                            });
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            final String responseData = response.body().string();
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        JSONObject jsonObject = new JSONObject(responseData);
                                        if (jsonObject.getString("code").equals("200")) {
                                            Toast.makeText(RegisterActivity.this, "注册成功", Toast.LENGTH_SHORT).show();
                                            Intent intent = new Intent(RegisterActivity.this, RobotActivity.class);
                                            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                            Bundle bundle = ActivityOptionsCompat.makeCustomAnimation(RegisterActivity.this,
                                                    android.R.anim.fade_in, android.R.anim.fade_out).toBundle();
                                            startActivity(intent, bundle);
                                            finish();
                                        }
                                        else
                                        {
                                            Toast.makeText(RegisterActivity.this, jsonObject.getString("msg"), Toast.LENGTH_SHORT).show();
                                        }
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            });
                        }
                    });
                }
            }
        });

    }

    private void getArray(JSONObject jsonObject,List<String> array,List<String> id) throws JSONException {
        JSONArray jsonArray = jsonObject.getJSONArray("data");
        if(jsonArray.length()>0){
            for(int i=0;i<jsonArray.length();i++){
                JSONObject object = jsonArray.getJSONObject(i);
                array.add(object.getString("classesName"));
                id.add(object.getString("classesId"));
            }
        }
    }
}



